package mscloud.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
@Slf4j
public class FinalConfigCheck {

    @Value("${spring.redis.host:未加载}")
    private String redisHost;

    @Value("${spring.redis.port:0}")
    private int redisPort;

    @Value("${spring.redis.password:未加载}")
    private String redisPassword;

    @Value("${spring.redis.database:0}")
    private int redisDatabase;

    @Value("${verify.captcha.enabled:false}")
    private boolean captchaEnabled;

    @Value("${verify.captcha.type:未加载}")
    private String captchaType;

    @Autowired(required = false)
    private LettuceConnectionFactory lettuceConnectionFactory;

    @EventListener(ApplicationReadyEvent.class)
    public void finalCheck() {
        log.info("📋 从 Nacos 加载的配置:");
        log.info("  Redis Host: {}", redisHost);
        log.info("  Redis Port: {}", redisPort);
        log.info("  Redis Password: {}", redisPassword.equals("未加载") ? "❌ 未加载" : "✅ 已加载");
        log.info("  Redis Database: {}", redisDatabase);
        log.info("  Captcha Enabled: {}", captchaEnabled);
        log.info("  Captcha Type: {}", captchaType);

        log.info("\n🔧 Lettuce 连接工厂配置:");
        if (lettuceConnectionFactory != null) {
            log.info("  实际连接 Host: {}", lettuceConnectionFactory.getHostName());
            log.info("  实际连接 Port: {}", lettuceConnectionFactory.getPort());
            log.info("  实际连接 Database: {}", lettuceConnectionFactory.getDatabase());
        } else {
            log.warn("  ⚠️ LettuceConnectionFactory 未注入");
        }

        boolean nacosConfigLoaded = !redisHost.equals("未加载")
                && redisPort != 0
                && !redisPassword.equals("未加载")
                && redisDatabase == 2; // 假设 Nacos 配置应为 2

        boolean lettuceConfigCorrect = lettuceConnectionFactory != null
                && redisHost.equals(lettuceConnectionFactory.getHostName())
                && redisPort == lettuceConnectionFactory.getPort()
                && redisDatabase == lettuceConnectionFactory.getDatabase();

        log.info("\n📊 配置状态总结:");
        log.info("  Nacos 配置加载: {}", nacosConfigLoaded ? "✅ 成功" : "❌ 失败");
        log.info("  Lettuce 工厂配置: {}", lettuceConfigCorrect ? "✅ 正确" : "❌ 不正确");

        if (nacosConfigLoaded && lettuceConfigCorrect) {
            log.info("🎉 配置完全成功！Redis 连接应该可以正常工作了！");
        } else if (nacosConfigLoaded) {
            log.warn("⚠️  Nacos 配置已加载，但 Lettuce 工厂可能需要重启应用才能生效");
        } else {
            log.error("❌ 配置仍有问题，需要进一步排查");
        }
    }
}
